#include "answereditvariant.h"
#include "ui_answereditvariant.h"
#include "WidgetTextEdit.h"

#include "mylistitem.h"
#include <QMessageBox>
#include <QInputDialog>
#include <QLabel>
#include <QSqlError>



AnswerEditVariant::AnswerEditVariant(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::AnswerEditVariant)
{
    m_ui->setupUi(this);
    db = new CDBProvider();
    //m_ui->listWidget->setModel(
}

AnswerEditVariant::~AnswerEditVariant()
{
    delete m_ui;
}

void AnswerEditVariant::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
QGridLayout * AnswerEditVariant::getGrid(){
    return m_ui->gridLayout;
}

void AnswerEditVariant::on_addAnswer_clicked()
{
    QString name = trUtf8("Ответ №") + QString::number(m_ui->listWidget->count()+1);
    MyListItem *i = new MyListItem(name);
    i->setCheckState(Qt::Unchecked);
    i->setData(QVariant(QString("")));
    i->id_task = idTask;
    m_ui->listWidget->addItem(i);
    db->saveAnswer(i);
}

void AnswerEditVariant::on_deleteAnswer_clicked()
{
    MyListItem * i = (MyListItem *)m_ui->listWidget->currentItem();
    db->deleteAnswerFromDB(i->id->toInt());
    delete(m_ui->listWidget->currentItem());
}

void AnswerEditVariant::on_rightAnswer_clicked()
{
//    QListWidgetItem *i = m_ui->listWidget->currentItem();
//    if(i == NULL) return;
//    i->setCheckState(i->checkState()==Qt::Unchecked?Qt::Checked:Qt::Unchecked);
}

void AnswerEditVariant::on_listWidget_currentItemChanged(QListWidgetItem* current, QListWidgetItem* previous)
{
    if(wait)return;
    if(previous)
        ((MyListItem *)previous)->setData(QVariant(textEditor->getHtmlText()));
    textEditor->fileNew(true);
    if(current)
        if(((MyListItem *)current)->data != NULL)
            textEditor->setHtmlText(((MyListItem *)current)->data->toString());
}

void AnswerEditVariant::loadAnswerFromDB(int taskId){
    wait = true;
    m_ui->listWidget->clear();
    for(int i=0; i <m_ui->listWidget->count();++i){
        MyListItem *y = (MyListItem *)m_ui->listWidget->item(i);
        delete y;
    }

    foreach(MyListItem * i, db->getAnswer(taskId)){
     m_ui->listWidget->addItem(i);
    }
    wait=false;
}


void AnswerEditVariant::setIdTask(int taskId){
    if(taskId == 0){
        setEnabled(false);
        return;
    }
    idTask = taskId;
    loadAnswerFromDB(taskId);
}

void AnswerEditVariant::on_listWidget_itemChanged(QListWidgetItem* item)
{
    //QMessageBox::information(this,"dsfdsfds",((MyListItem *)item)->id->toString());
    db->saveAnswer((MyListItem *)item);
}
